﻿using STHPMS1.BLL.B_Core;
using STHPMS1.Common.C_Entity.Stmpms1;
using STHPMS1.ICore.I_BLL.Bus;
using STHPMS1.ICore.I_Entity.Info;
using STHPMS1.ICore.I_Entity.Stmpms1;
using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Linq;
using STHPMS1.Common.C_Enum;
using STHPMS1.Common.C_Extension;
using STHPMS1.ICore.I_DAL;

namespace STHPMS1.BLL.B_Bus
{
    public class Dm_HistperfBus : BllBase, IDm_HistperfBill
    {
        public void Save<T>(T entity)
            where T : class ,IDm_Histperf
        {
            if (this.Scene.Dal.Sthpms1.Update(entity) == 0)
            {
                this.Scene.Dal.Sthpms1.Insert(entity);
            }
        }

        public void Remove(IDm_Histperf entity)
        {
            this.Scene.Dal.Sthpms1.Delete(entity);
        }

        public IEnumerable<T> Get<T>(Expression<Func<T, bool>> predicate, IPagingInfo info)
            where T : class, IDm_Histperf
        {
            return this.Scene.Dal.Sthpms1.Select<T>(predicate, info);
        }

        public void CalacModelIndicator(string inspecid)
        {
            ISthpms1Dao dao = this.Scene.Dal.Sthpms1;

            S_Inspeaccse speaccse = dao.SingleById<S_Inspeaccse>(inspecid);
            short year = ConvertYear(speaccse.Year_M);

            List<E_Roadwaydetail> detailList = dao.Select<E_Roadwaydetail>(p => p.Year_M.StartsWith(year.ToString()));
            List<Dm_Histperf> perfList=new List<Dm_Histperf>();

            if (detailList.Count == 0) return;
            foreach (var item in detailList.GroupBy(p=>p.Segid))
	        {
                List<E_Roadwaydetail> list = item.ToList();

                Dm_Histperf perf =new Dm_Histperf();
                perf.Segid = list[0].Segid;
                perf.Rdwayid = list[0].Rdwayid;
                perf.Perfyear = ConvertYear(list[0].Year_M);
                perf.Pciave = list.Average(p => p.Pci);
                perf.Pssave = list.Average(p => p.Pssi);

                B_Invntory invntory = dao.SingleById<B_Invntory>(list[0].Segid);
                if (invntory == null) throw new Exception("路段信息没有找到-"+list[0].Segid);
                Dm_Esalage esal = dao.Single<Dm_Esalage>(p => p.Segid == list[0].Segid && p.Perfyear == (perf.Perfyear - invntory.Begindate.Value.Year));
                if (esal != null)
                {
                    perf.Histaadt = esal.Aadt;
                    perf.Easl_All = esal.Easl;
                    perf.Modelgroup_Id = invntory.Modelgroup_Pci;
                }
                perfList.Add(perf);
	        }

            dao.SaveAll(perfList);
        }

        private short ConvertYear(string y)
        {
            short year = 0;
            try
            {
                year=Convert.ToInt16(y.Substring(0, 4));
            }
            catch (Exception)
            {
                throw new Exception("转换评定管理年份错误-" + y);
            }
            return year;
        }

    }
}
